﻿using Identity_JWT_WebAPI.Dao;
using Identity_JWT_WebAPI.Dao.Model;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Runtime.CompilerServices;

namespace Identity_JWT_WebAPI
{
    public  static class RegisterIdentity
    {
       
        public static WebApplicationBuilder AddIdentity(this WebApplicationBuilder builder) 
        {
            var services = builder.Services;
            services.AddDataProtection();
            //services.Configure<IdentityOptions>(options =>
            services.AddIdentityCore<User>(options =>  //注意这里使用的是AddIdentityCore<User>
            {
                // Password settings.
                options.Password.RequireDigit = true;  //必须有数字
                options.Password.RequireLowercase = false;  //至少有一个小写字母
                options.Password.RequireNonAlphanumeric = false;  //至少有一个除字母和数字以外的字符
                options.Password.RequireUppercase = false;  //大写
                options.Password.RequiredLength = 6;
                options.Password.RequiredUniqueChars = 1;

                // Lockout settings.
                options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);  //5分钟
                options.Lockout.MaxFailedAccessAttempts = 5;   //密码验证失败5则锁定
                options.Lockout.AllowedForNewUsers = true;

                //重置密码用这种配置验证码短少，不配置验证码长
                options.Tokens.PasswordResetTokenProvider = TokenOptions.DefaultEmailProvider;
                options.Tokens.EmailConfirmationTokenProvider = TokenOptions.DefaultEmailProvider;

                // User settings.
                options.User.AllowedUserNameCharacters =
                "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";  //用户名只能在该字符中组合
                options.User.RequireUniqueEmail = false;  //邮箱是否必须是唯一的
            });
            IdentityBuilder idBuilder = new IdentityBuilder(typeof(User), typeof(Role), services);
            idBuilder.AddDefaultTokenProviders();
            idBuilder.AddEntityFrameworkStores<MyDbContext>()
            .AddRoleManager<RoleManager<Role>>()
            .AddUserManager<UserManager<User>>();

            return builder;
        }
    }
}
